// file_saver.dart
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'dart:html' as html;

import 'package:path_provider/path_provider.dart';

class FileSaver {
  /// 将数据保存为文件（浏览器会弹出下载）
  static void saveFile(Uint8List bytes, String fileName) {
    if (kIsWeb) {
      _saveFileWeb(bytes, fileName);
    } else {
      _saveFileNative(bytes, fileName);
    }
  }

  // ✅ Web 实现：创建 blob URL 并触发下载
  static void _saveFileWeb(Uint8List bytes, String fileName) {
    final blob = html.Blob([bytes]);
    final url = html.Url.createObjectUrlFromBlob(blob);
    final anchor = html.AnchorElement(href: url)
      ..target = 'blank'
      ..download = fileName;
    anchor.click();
    html.Url.revokeObjectUrl(url); // 清理
  }

  // ✅ 原生实现：写入临时目录
  static void _saveFileNative(Uint8List bytes, String fileName) async {
    final dir = await getTemporaryDirectory();
    final file = File('${dir.path}/$fileName');
    await file.writeAsBytes(bytes);
    print("文件已保存到: ${file.path}");
  }
}